package org.exmaple.springframework.beans.factory.support;

import org.exmaple.springframework.beans.BeansException;
import org.exmaple.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;

/**
 * @author DeYou
 * @date 2022/10/27
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy{
    /**
     * JDK 实例化策略
     * @param beanDefinition
     * @param beanName
     * @param ctor
     * @param args
     * @return
     */
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) {
        Class beanClass = beanDefinition.getBeanClass();
        try{
            if (Objects.nonNull(ctor)) {
                return beanClass.getDeclaredConstructor( ctor.getParameterTypes() ).newInstance( args );
            }else {
                return beanClass.getDeclaredConstructor().newInstance();
            }

        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new BeansException("Failed to instantiate [" + beanClass.getName() + "]", e);
        }



    }
}